/**
 * 
 */
package jvs.vfs.opt.contact;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.Contacts;
import android.provider.Contacts.ContactMethods;
import android.provider.Contacts.ContactMethodsColumns;
import android.provider.Contacts.People;
import android.provider.Contacts.PeopleColumns;
import android.text.TextUtils;
import android.util.Log;

/**
 * @author qiangli
 * 
 */

public class ContactAdapter1 extends ContactAdapter {

	private static final String LOG_TAG = "ContactAdapter1";

	public ContactAdapter1() {
	}

	@Override
	protected void loadFavoriteInContact(Context ctx, Set<ContactInfo> contacts) {
		String sel = PeopleColumns.STARRED + " != 0 AND "
				+ ContactMethodsColumns.KIND + " in (1, 3)"; // email and im
		loadEmailContact(ctx, sel, contacts);
	}

	@Override
	protected void loadContactsInContact(Context ctx, Set<ContactInfo> contacts) {
		String sel = ContactMethodsColumns.KIND + " in (1, 3)"; // email and im
		loadEmailContact(ctx, sel, contacts);
	}

	private void loadEmailContact(Context ctx, String sel,
			Set<ContactInfo> contacts) {
		Uri uri = Contacts.ContactMethods.CONTENT_URI;
		String[] proj = new String[] { ContactMethods.PERSON_ID,
				PeopleColumns.DISPLAY_NAME, PeopleColumns.STARRED,
				PeopleColumns.LAST_TIME_CONTACTED,
				PeopleColumns.TIMES_CONTACTED, PeopleColumns.PHONETIC_NAME,
				ContactMethodsColumns.KIND, ContactMethodsColumns.DATA };
		String by = PeopleColumns.DISPLAY_NAME + " ASC, "
				+ ContactMethodsColumns.DATA + " ASC ";

		ContentResolver cr = ctx.getContentResolver();
		Cursor c = cr.query(uri, proj, sel, null, by);
		//
		if (c == null) {
			return;
		}
		try {
			if (DEBUG) {
				Log.d(LOG_TAG, "loadContactsInConact count: " + c.getCount());
			}
			if (!c.moveToFirst()) {
				return;
			}
			//
			int colId = c.getColumnIndex(ContactMethods.PERSON_ID);
			int colName = c.getColumnIndex(PeopleColumns.DISPLAY_NAME);
			int colStar = c.getColumnIndex(PeopleColumns.STARRED);
			int colPName = c.getColumnIndex(PeopleColumns.PHONETIC_NAME);
			int colEmail = c.getColumnIndex(ContactMethodsColumns.DATA);
			int colLastTime = c
					.getColumnIndex(PeopleColumns.LAST_TIME_CONTACTED);
			int colTimes = c.getColumnIndex(PeopleColumns.TIMES_CONTACTED);
			String prev = "";
			ContactInfo ec = null;
			ArrayList<String> el = new ArrayList<String>(); // emails
			do {
				String n = c.getString(colName);
				if (n.equals(prev)) {
					String s = c.getString(colEmail);
					//
					if (!el.contains(s)) {
						el.add(s);
					}
					//
					//
					ec.lastTime = Math.max(ec.lastTime, c.getLong(colLastTime));
					ec.times += c.getInt(colTimes);
				} else {
					// new entry
					if (ec != null) {
						ec.emails = el.toArray(new String[0]);
						contacts.add(ec);
					}
					//
					ec = new ContactInfo();
					el.clear();
					prev = n;
					//
					ec.id = c.getString(colId);
					ec.name = n;
					ec.phoneticName = c.getString(colPName);
					ec.starred = c.getInt(colStar);
					ec.lastTime = c.getLong(colLastTime);
					ec.times = c.getInt(colTimes);
					//
					ec.sortkey = n;
					//
					String s = c.getString(colEmail);
					el.add(s);
				}
			} while (c.moveToNext());
			if (ec != null) {
				ec.emails = el.toArray(new String[0]);
				contacts.add(ec);
			}
		} finally {
			c.close();
		}
	}

	@Override
	protected void loadGroupNamesInConact(Context ctx, Set<String> names) {
		Uri uri = Contacts.ContactMethods.CONTENT_URI;
		String[] proj = new String[] { ContactMethods._ID,
				PeopleColumns.DISPLAY_NAME, ContactMethodsColumns.KIND,
				ContactMethodsColumns.DATA };
		String by = PeopleColumns.DISPLAY_NAME + " ASC";
		String sel = PeopleColumns.DISPLAY_NAME + " like ? AND "
				+ ContactMethodsColumns.KIND + " in (1, 3)"; // email and im
		String[] args = new String[] { "@%" };
		ContentResolver cr = ctx.getContentResolver();
		Cursor c = cr.query(uri, proj, sel, args, by);
		if (c == null) {
			return;
		}
		try {
			if (!c.moveToFirst()) {
				return;
			}
			int colName = c.getColumnIndex(People.DISPLAY_NAME);
			int colEmail = c.getColumnIndex(ContactMethodsColumns.DATA);
			do {
				String a = c.getString(colEmail);
				if (TextUtils.isEmpty(a)) {
					continue;
				}
				String n = c.getString(colName);
				names.add(n);
			} while (c.moveToNext());
		} finally {
			c.close();
		}
	}

	@Override
	protected boolean hasEmailInContact(Context context, String email) {
		Uri uri = Contacts.ContactMethods.CONTENT_URI;
		String[] proj = new String[] { android.provider.BaseColumns._ID,
				PeopleColumns.DISPLAY_NAME, ContactMethodsColumns.DATA };
		String sel = ContactMethodsColumns.DATA + "= ?";
		String[] args = new String[] { email };
		Cursor c = context.getContentResolver().query(uri, proj, sel, args,
				null);
		if (c == null) {
			return false;
		}
		try {
			return (c.moveToFirst());
		} finally {
			c.close();
		}
	}

	@Override
	protected String[] getEmailsInContact(Context ctx, String name) {
		Uri uri = Contacts.ContactMethods.CONTENT_URI;
		String[] proj = new String[] { PeopleColumns.DISPLAY_NAME,
				ContactMethodsColumns.DATA };
		String sel = PeopleColumns.DISPLAY_NAME + "= ?";
		String[] args = new String[] { name };
		Cursor c = ctx.getContentResolver().query(uri, proj, sel, args, null);
		if (c == null) {
			return null;
		}
		try {
			if (!c.moveToFirst()) {
				return null;
			}
			//
			int colEmail = c.getColumnIndex(ContactMethodsColumns.DATA);
			Set<String> set = new HashSet<String>();
			do {
				String s = c.getString(colEmail);
				set.add(s);
			} while (c.moveToNext());
			return set.toArray(new String[0]);
		} finally {
			c.close();
		}
	}

	@Override
	protected long getContactId(Context context, String name) {
		String[] proj = new String[] { People._ID, PeopleColumns.DISPLAY_NAME, };
		Cursor c = context.getContentResolver().query(People.CONTENT_URI, proj,
				PeopleColumns.DISPLAY_NAME + " = ?", new String[] { name },
				null);
		if (c == null) {
			return -1;
		}
		try {
			if (!c.moveToFirst()) {
				return -1;
			}
			// return the first one found, assuming name is unique
			int idCol = c.getColumnIndex(People._ID);
			return c.getLong(idCol);
		} finally {
			c.close();
		}
	}

	@Override
	public void loadPhoneContacts(Context ctx, List<ContactInfo> contacts,
			int idx, String by) {
		loadPhoneContacts(ctx, null, contacts, idx, by);
	}

	private void loadPhoneContacts(Context ctx, String sel,
			List<ContactInfo> contacts, int idx, String sortby) {
		Uri uri = Contacts.Phones.CONTENT_URI;
		String[] proj = new String[] { Contacts.Phones._ID,
				Contacts.Phones.PERSON_ID, PeopleColumns.DISPLAY_NAME,
				PeopleColumns.STARRED, PeopleColumns.LAST_TIME_CONTACTED,
				PeopleColumns.TIMES_CONTACTED, PeopleColumns.PHONETIC_NAME,
				Contacts.Phones.TYPE, Contacts.Phones.LABEL,
				Contacts.Phones.NUMBER };
		
		ContentResolver cr = ctx.getContentResolver();
	
		Cursor c = cr.query(uri, proj, sel, null, sortby);
		//
		if (c == null) {
			return;
		}
		try {
			if (DEBUG) {
				Log.d(LOG_TAG, "loadPhoneContacts count: " + c.getCount()
						+ " sort: " + sortby);
			}
			if (!c.moveToFirst()) {
				return;
			}
			//
			int colId = c.getColumnIndex(Contacts.Phones._ID);
			int colCid = c.getColumnIndex(Contacts.Phones.PERSON_ID);
			int colName = c.getColumnIndex(PeopleColumns.DISPLAY_NAME);
			int colPName = c.getColumnIndex(PeopleColumns.PHONETIC_NAME);
			int colStar = c.getColumnIndex(PeopleColumns.STARRED);
			int colNumber = c.getColumnIndex(Contacts.Phones.NUMBER);
			int colType = c.getColumnIndex(Contacts.Phones.TYPE);
			int colLabel = c.getColumnIndex(Contacts.Phones.LABEL);
			int colLastTime = c
					.getColumnIndex(PeopleColumns.LAST_TIME_CONTACTED);
			int colTimes = c.getColumnIndex(PeopleColumns.TIMES_CONTACTED);

			long sortkey = System.currentTimeMillis();
			do {
				ContactInfo ec = new ContactInfo();
				String num = c.getString(colNumber);
				if (TextUtils.isEmpty(num)) {
					continue;
				}
				ec.index = idx;
				ec.phone = num;
				ec.id = c.getString(colId);
				ec.cid = c.getLong(colCid);
				ec.name = c.getString(colName);
				ec.phoneticName = c.getString(colPName);
				ec.starred = c.getInt(colStar);
				ec.lastTime = c.getLong(colLastTime);
				ec.times = c.getInt(colTimes);
				int type = c.getInt(colType);
				int pType = ContactInfo.TYPE_OTHER;
				switch (type) {
				case Contacts.Phones.TYPE_HOME:
					pType = ContactInfo.TYPE_HOME;
					break;
				case Contacts.Phones.TYPE_WORK:
					pType = ContactInfo.TYPE_WORK;
					break;
				case Contacts.Phones.TYPE_MOBILE:
					pType = ContactInfo.TYPE_MOBILE;
					break;
				case Contacts.Phones.TYPE_CUSTOM:
					pType = ContactInfo.TYPE_CUSTOM;
					break;
				case Contacts.Phones.TYPE_OTHER:
					pType = ContactInfo.TYPE_OTHER;
					break;
				}
				ec.phoneType = pType;
				ec.phoneLabel = c.getString(colLabel);

				sortkey++;
				ec.sortkey = sortkey + "";
				//
				contacts.add(ec);
				//
				if (DEBUG) {
					Log.d(LOG_TAG, "loadPhoneContacts added. sortkey: "
							+ sortkey + " " + ec);
				}
			} while (c.moveToNext());
		} finally {
			c.close();
		}
	}

	@Override
	public void loadPhoneFavorite(Context ctx, List<ContactInfo> contacts,
			int idx, String by) {
		String sel = PeopleColumns.STARRED + " != 0 ";
		loadPhoneContacts(ctx, sel, contacts, idx, by);
	}

}
